<template>
  <div class="topo-render" :style="layerStyle" v-if="configData && configData.layer">
    <div>{{ shopNumber }}</div>
    <template v-for="(component, index) in configData.components">
      <div
        class="topo-render-wrapper"
        :key="index"
        @click="doClickComponent(component)"
        @dblclick="doDbClickComponent(component)"
        :class="{
          'topo-render-wrapper-clickable': component.action.length > 0
        }"
        v-show="
          component.style.visible == undefined ? true : component.style.visible
        "
        :style="{
          left: component.style.position.x + 'px',
          top: component.style.position.y + 'px',
          width: component.style.position.w + 'px',
          height: component.style.position.h + 'px',
          backgroundColor: component.style.backColor,
          zIndex: component.style.zIndex,
          borderWidth: component.style.borderWidth + 'px',
          borderStyle: component.style.borderStyle,
          borderColor: component.style.borderColor,
           animation:component.style.animation,
          transform: (component.style.rotateX
            ? `rotateX(${component.style.rotateX}deg)`
            : 'rotateX(0deg)')+''+(component.style.rotateY
            ? `rotateY(${component.style.rotateY}deg)`
            : 'rotateY(0deg)')+''+(component.style.rotateZ
            ? `rotateZ(${component.style.rotateZ}deg)`
            : 'rotateZ(0deg)'),
        }"
      >
        <component v-bind:is="parseView(component)" :detail="component" ref="spirit" />
      </div>
    </template>
    <!-- 制冷机 -->
    <q-dialog v-model="refrigeratorDialog">
      <refrigerator :dialogData="dialogData" :index="index" :nums="getCompomentsByCode('CHL')"></refrigerator>
    </q-dialog>
    <!-- 冷却塔 -->
    <q-dialog v-model="coolingTowerDialog">
      <cooling-tower :dialogData="dialogData" :index="index" :nums="getCompomentsByCode('CT')"></cooling-tower>
    </q-dialog>
    <!-- 冷却泵+冷冻泵 -->
    <q-dialog v-model="coolingPumpDialog">
      <cooling-pump :dialogData="dialogData" :index="index" :nums="coolingPumpNums"></cooling-pump>
    </q-dialog>
  </div>
</template>

<script>
import TopoBase from "./TopoBase";
import topoUtil from "./util/topo-util";
import { mapGetters, mapMutations } from "vuex";
import dataList from "@/mock/result.js";
import { initWebSocket } from "@/assets/libs/websocket";
import { detailDesigner } from "@/services/index.js";
import Regexps from "@/assets/libs/regexp.js";
import CoolingPump from "./sub-pages/CoolingPump";
import CoolingTower from "./sub-pages/CoolingTower";
import Refrigerator from './sub-pages/Refrigerator';
import { lastChar } from "@/assets/libs/utils.js";

export default {
  name: "TopoRender",
  extends: TopoBase,
  components: { Refrigerator, CoolingPump, CoolingTower },
  computed: {
    layerStyle: function () {
      var styles = [];
      if (this.configData) {
        if (this.configData.layer.backColor) {
          styles.push(`background-color: ${this.configData.layer.backColor}`);
        }
        if (this.configData.layer.backgroundImage) {
          styles.push(
            `background-image: url("${this.configData.layer.backgroundImage}")`
          );
        }
        if (this.configData.layer.width > 0) {
          styles.push(`width: ${this.configData.layer.width}px`);
        }
        if (this.configData.layer.height > 0) {
          styles.push(`height: ${this.configData.layer.height}px`);
        }
      }
      var style = styles.join(";");
      return style;
    },
    ...mapGetters("topoEditor", {
      curShopInfo: "getShopInfo",
      shopNumber: "getShopNumber"
    })
  },
  data () {
    return {
      websocketInstance: null, //websocket对象
      dataList,
      configData: null,
      coolingPumpDialog: false, //冷却泵、冷冻泵
      dialogData: { text: "", dataList: [] },
      index: 0,
      coolingTowerDialog: false,//冷却塔
      refrigeratorDialog: false,//制冷机
      coolingPumpNums: 0 //冷却泵、冷冻泵数量
    };
  },
  created () {
    // detailDesigner(this.shopNumber).then(res => {
    //   if (res.code == 200 && res.data) {
    //     this.configData = JSON.parse(res.data.json);
        if (this.websocketInstance == null) {
          this.websocketInstance = this.createdSocket();
        }
    //   }
    // });
  },
  methods: {
    //根据编码获取组件个数
    getCompomentsByCode (code) {
      return this.configData.components.filter(n => n.code == code).length;
    },
    ...mapMutations("topoEditor", ["setTopoData"]),
    //创建socket对象
    createdSocket () {
      let that = this;
      return initWebSocket(
        { shopNumber: that.shopNumber },
        function (result) {
          console.log("收到监测的消息", result);
          that.dataList = result;
          that.dialogData.dataList = that.dataList.data.list;
          that.refreshData();
        },
        "/ws/safeManage/air/websocket"
      );
    },
    // 刷新configData.components数据
    refreshData () {
      let that = this;
      console.log("this.configData :", this.configData);
      this.configData.components.forEach(n => {
        n = that.structureData(n);
      });
      // this.setTopoData(this.configData);
    },
    // 构造数据--数据动态绑定
    structureData (component) {
      if (
        this.dataList.data &&
        this.dataList.data.list.length > 0 &&
        component.dataBind.text
      ) {
        let dataBind = this.dataList.data.list.find(n => {
          return n.Address == component.dataBind.text;
        });
        if (dataBind) {
          //能找到绑定数据
          component.dataItem = dataBind;
        } else {
          //找不到的，绑定图片
          component.dataItem = { val: 0 };
          this.structureComponentImgUrl(component);
        }
        // 0:正常，1：掉线，2：异常  掉线的时候，线条就不动
        if (component.style.animations && component.dataBind.val == 0) {
          component.style.animations = undefined;
        }
        return component;
      }
      return component;
    },
    //构造组件图片
    structureComponentImgUrl (component) {
      let list = this.dataList.data.list;
      let baseDir = "statics/topo/cold-tools/";
      let address = component.dataBind.text;
      let dataBind = null; //.Address.replace("/", "_");
      // 冷机
      if (Regexps.CHL.test(address)) {
        // - 正常
        dataBind = list.find(n => {
          return n.Address == address + "_PWR";
        });
        if (dataBind && dataBind.val > 0) {
          component.style.url = baseDir + "Chl1.png";
        } else {
          dataBind = list.find(n => {
            return n.Address == address + "_ALM";
          });
          if (dataBind && dataBind.val > 0) {
            //报警
            component.style.url = baseDir + "ChlAlarm.png";
          }
        }
        // console.log('冷机 address :', address);
      }
      //冷冻泵 or 冷却泵
      else if (Regexps.CHWP.test(address) || Regexps.CWP.test(address)) {
        dataBind = list.find(n => {
          return n.Address == address + "_PWR";
        });
        if (dataBind && dataBind.val > 0) {
          component.style.url = baseDir + "Cwp1.png";
        } else {
          dataBind = list.find(n => {
            return n.Address == address + "_VFD_ALM";
          });
          if (dataBind && dataBind.val > 0) {
            component.style.url = baseDir + "CwpAlarm.png";
          }
        }
        // console.log('冷冻泵 address :', address);
      }
      //冷却塔--风扇
      else if (Regexps.CT.test(address)) {
        dataBind = list.find(n => {
          return n.Address == address + "_PWR";
        });
        if (dataBind && dataBind.val > 0) {
          if (component.code == "fan") {
            component.style.url = baseDir + "fs.gif";
          } else {
            component.style.url = baseDir + "Ct1.png";
          }
        } else {
          dataBind = list.find(n => {
            return n.Address == address + "_VFD_ALM";
          });
          if (dataBind && dataBind.val > 0) {
            if (component.code == "fan") {
              component.style.url = "";
            } else {
              component.style.url = baseDir + "CtAlarm.png";
            }
          } else {
            if (component.code == "fan") {
              component.style.url = "";
            } else {
              component.style.url = baseDir + "Tower_60_64.png";
            }
          }
        }
        console.log("冷却塔 address :", address);
      }

      console.log(" component.style.url :", component.style.url);
    },
    // 解析组件
    parseView (component) {
      return topoUtil.parseViewName(component);
    },
    doClickComponent (component) {
      for (var i = 0; i < component.action.length; i++) {
        var action = component.action[i];
        if (action.type == "click") {
          this.handleComponentActuib(action, component);
        }
      }
    },
    doDbClickComponent (component) {
      for (var i = 0; i < component.action.length; i++) {
        var action = component.action[i];
        if (action.type == "dblclick") {
          this.handleComponentActuib(action);
        }
      }
    },
    handleComponentActuib (action, component) {
      var _this = this;
      if (action.action == "visible") {
        if (action.showItems.length > 0) {
          action.showItems.forEach(identifier => {
            _this.showComponent(identifier, true);
          });
        }
        if (action.hideItems.length > 0) {
          action.hideItems.forEach(identifier => {
            _this.showComponent(identifier, false);
          });
        }
      } else if (action.action == "service") {
        _this.sendFun(action, component);
      }
    },
    showComponent (identifier, visible) {
      console.log("show:" + identifier + ",visible:" + visible);
      var spirits = this.$refs["spirit"];
      for (var i = 0; i < spirits.length; i++) {
        var spirit = spirits[i];
        if (spirit.detail.identifier == identifier) {
          spirit.detail.style.visible = visible;
          break;
        }
      }
    },
    //调用服务
    sendFun (action, component) {
      console.log("action :", action, component);
      if (component.dataBind.text) {
        this.index = parseInt(lastChar(component.dataBind.text));
      }

      switch (component.code) {
        case "CHL": //制冷机
          this.refrigeratorDialog = true;
          this.dialogData.text = this.index + "#制冷机";
          break;
        case "CT": //冷却塔
          this.coolingTowerDialog = true;
          this.dialogData.text = this.index + "#冷却塔";
          break;
        case "CHWP": //冷冻泵
          this.coolingPumpDialog = true;
          this.dialogData.text = this.index + "#冷冻泵";
          this.coolingPumpNums = this.getCompomentsByCode('CHWP');
          break;
        case "CWP": //冷却泵
          this.coolingPumpDialog = true;
          this.dialogData.text = this.index + "#冷却泵";
          this.coolingPumpNums = this.getCompomentsByCode('CWP');
          break;
        case "DV":
          break;
        case "heat-CHWP":
          break;
        default:
          break;
      }
      console.log("点击了" + component.dataBind.text);
    }
  },
  destroyed () {
    if (this.websocketInstance) {
      this.websocketInstance.close();
      this.websocketInstance = null;
    }
  }
};
</script>

<style lang="scss">
.topo-render {
  overflow: auto;
  background-color: white;
  background-clip: padding-box;
  background-origin: padding-box;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: relative;
  height: 100%;

  .topo-render-wrapper {
    position: absolute;
  }

  .topo-render-wrapper-clickable {
    cursor: pointer;
  }
  .q-dialog__inner--minimized > div.cooling-pump {
    width: 720px;
  }
}
</style>
